#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :video_md5.py
# @Time      :2025/7/5 09:53
# @Author    :Ethon

import os
import hashlib
from datetime import datetime


def calculate_video_md5(file_path, buffer_size=65536):
    """
    计算视频文件的MD5哈希值

    :param file_path: 视频文件路径
    :param buffer_size: 每次读取的字节数
    :return: 视频文件的MD5哈希字符串
    """
    md5 = hashlib.md5()

    try:
        with open(file_path, 'rb') as f:
            while True:
                data = f.read(buffer_size)
                if not data:
                    break
                md5.update(data)
        return md5.hexdigest()
    except FileNotFoundError:
        print(f"错误：文件 '{file_path}' 未找到")
        return None
    except Exception as e:
        print(f"计算MD5时发生错误: {str(e)}")
        return None


def change_md5_with_empty_byte(input_file, output_file):
    with open(input_file, 'rb') as f_in:
        data = f_in.read()

    # 在文件末尾追加一个空字节（0x00）
    with open(output_file, 'wb') as f_out:
        f_out.write(data + b'\x00')


# 提示
def print_md5(md5_hash):
    if md5_hash:
        print(f"生成的视频文件的MD5哈希值为: {md5_hash}")
    else:
        print("生成的视频文件的MD5哈希值计算失败")


def generate_video_md5(original_video_name):
    '''
    :param original_video_name: 原始视频文件名
    '''
    current_time = datetime.now().strftime('%Y%m%d%H%M%S')
    generated_video_name = original_video_name.split('.')[0] + '-' + current_time + '.mp4'

    original_file_path = os.path.join(os.getcwd(), 'source', original_video_name)
    generated_file_path = os.path.join(os.getcwd(), 'genera', generated_video_name)

    # 计算原始视频文件的MD5哈希值
    original_md5_hash = calculate_video_md5(original_file_path)
    print_md5(original_md5_hash)

    # 使用示例
    change_md5_with_empty_byte(original_file_path, generated_file_path)

    # 计算生成视频文件的MD5哈希值
    generated_md5_hash = calculate_video_md5(generated_file_path)
    print_md5(generated_md5_hash)


if __name__ == "__main__":
    '''
    将原始视频放入source文件夹，将需要修改的视频文件名填写至original_video_name中
    运行即可计算原始视频文件的MD5哈希值，并在不影响视频内容的情况下，生成一个新的视频文件，并计算生成视频文件的MD5哈希值
    '''
    original_video_name = '混剪.mp4'
    generate_video_md5(original_video_name)
